<script setup>
import { ref, onBeforeUnmount, watch, defineProps, nextTick, onMounted } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';

const props = defineProps({
    ganderItemData: Object
})

// ========================== 数据 ==========================
const id = ref(null)
const dangerChart01 = ref(null)
const dangerdata = ref(null)
const worknote = ref([])
const dangerChart02 = ref(null)
const safeNote = ref([])
const isLoading = ref(false)

// 添加渲染状态标记
const isChartRendered = ref(false);
const resizeObserver = ref(null);

// 使用ref创建响应式option对象
const chartRefDanger = ref(null);
const chartRefSafe = ref(null);
let myChartSafe = null;
let myChartDanger = null;

const haddata1 = ref({
    timedata: [],
    valuedata: [],
    markAreaData: [],
    pieces: []
})
const haddata2 = ref({
    timedata: [],
    valuedata: [],
    markAreaData: [],
    pieces: []
})
let intervalId = null;

// ========================= 数据获取与更新 ========================
const fetchData = () => {
    console.log('fetchData');
    
    // if (!props.ganderItemData?.key) {
    //     return;
    // }
    try {
        console.log('fetchData->dangerDetail');
        console.log(props.ganderItemData.key);
        
        isLoading.value = true;
        fetchDangerData(props.ganderItemData.key)
    } catch (error) {
        console.error('数据请求失败', error);
    } finally {
        isLoading.value = false;
    }
}
// 获取
const fetchDangerData = async (dId) => {
    try {
        console.log('dangerDetail');
        
        const response = await axios.get(`http://192.168.31.96:5000/dangerCharts/${dId}`);
        id.value = response.data.data.id
        dangerChart01.value = response.data.data.dangerChart01
        dangerdata.value = response.data.data.dangerdata
        worknote.value = response.data.data.worknote
        dangerChart02.value = response.data.data.dangerChart02
        safeNote.value = [...worknote.value]; // 复制数组避免引用问题
        console.log("bbbbb",response.data);
        console.log('id',id.value);
        console.log('dangerChart01',dangerChart01.value);
        console.log('dangerdata', dangerdata.value);
        
        console.log('worknote',worknote.value);
        console.log('dangerChart02',dangerChart02.value);
        console.log('safeNote',safeNote.value);
        // 处理图表数据
        processChartData(haddata1.value, dangerChart01.value);
        processChartData(haddata2.value, dangerChart02.value);
        
    } catch (err) {
        console.error(err);
    } finally {
        if (worknote.value != [] && dangerChart02.value != {}) {
            isLoading.value = true
            nextTick(() => {
                // 渲染图表
                renderChart('danger');
                renderChart('safe');
            })
        }
        isLoading.value = false
        nextTick(() => {
            renderChart('danger')
        })
    }
}
// ======================== 图表数据处理 ========================
const processChartData = (target, source) => {
    if (!source) {
        return;
    }
    target.timedata = source.timedata || [];
    target.valuedata = source.valuedata || [];
    // 处理标记区域
    target.markAreaData = dangerdata.value.map(item => [
        { name: item.name, xAxis: item.begin},
        { xAxis: item.end }
    ]);
    // 处理颜色分段
    target.pieces.push({ lte: -1, color: 'green'}); // 不存在的索引前
    // 所有时间点的索引映射
    const timeIndexMap = target.timedata.reduce((acc, time, index) => {
        acc[time] = index;
        return acc;
    }, {})
    // 遍历所有时间点，生成颜色区间
    let lastEndIndex = -1;
    // 按照时间排序 dangerdata （确保不会重叠会顺序混乱）
    const sortedDangerData = [...dangerdata].sort((a, b) => a.begin.localeCompare(b.begin));
    sortedDangerData.forEach(item => {
        const beginIndex = timeIndexMap[item.begin];
        const endIndex = timeIndexMap[item.end];
        if (beginIndex !== undefined && endIndex !== undefined) {
            // 填充上一个区间到当前区间的绿色部分
            if (beginIndex > lastEndIndex + 1) {
                target.pieces.push({
                    gt: lastEndIndex,
                    lte: beginIndex - 1,
                    color: 'green'
                });
            }
            // 当前区间为红色
            target.pieces.push({
                gt: beginIndex - 1,
                lte: endIndex,
                color: 'red'
            });
            lastEndIndex = endIndex;
        }
    });
    // 添加最后一个绿色区间
    target.pieces.push({ gt: lastEndIndex, color: 'green'});
}

// ======================= 图表渲染 =======================
const renderChart = (type) => {
    nextTick(() => {
        try {
            const chartRef = type === 'danger' ? chartRefDanger : chartRefSafe;
            let chartInstance = type === 'danger' ? myChartDanger : myChartSafe;
            const data = type === 'danger' ? haddata1.value : haddata2.value;
            // 确保容器存在且可见
            if (!chartRef.value || chartRef.value.clientWidth === 0) {
                setTimeout(() => renderChart(type), 100);
                return;
            }
            // 清理旧实例
            if (chartInstance) {
                chartInstance.dispose();
                chartInstance = null;
            }
            // 创建新图表
            const option = {
                title: {
                    text: '告警详情',
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'cross',
                    }
                },
                toolbox: {
                    show: true,
                    feature: {
                        saveAsImage: {}
                    }
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: data.timedata
                },
                series: [
                    {
                        name: props.ganderItemData.name,
                        type: 'line',
                        smooth: true,
                        data: data.valuedata,
                        lineStyle: {
                            color: 'green'  // 这里可以设置任意颜色值，比如红色 '#ff0000'、蓝色 '#0000ff' 等
                        },
                        markArea: {
                            itemStyle: {
                                color: 'rgba(255, 173, 177, 0.4)',
                            },
                            data: data.markAreaData
                        }
                    }
                ],
                visualMap: {
                    show: false,
                    dimension: 0,
                    // pieces: data.pieces
                },
                yAxis: {
                    type: 'value',
                    axisLabel: {
                        formatter: '{value}'
                    },
                    axisPointer: {
                        snap: true
                    }
                },
            };
            chartInstance = echarts.init(chartRef.value)
            chartInstance.setOption(option);
            // 保存实例引用
            if (type === 'danger') {
                myChartDanger = chartInstance;
            } else {
                myChartSafe = chartInstance;
            }
            // 添加resize监听器
            const resizeHandler = () => chartInstance.resize()
            window.addEventListener('resize', resizeHandler);
            isChartRendered.value = true;
            // 清除回调
            onBeforeUnmount(() => {
                window.removeEventListener('resize', resizeHandler);
            });
        } catch (error) {
            console.error("渲染图表失败", error);
        }
    })
}


// ===================== 轮询控制 =======================
const startPolling = () => {
    if (intervalId) return;
    intervalId = setInterval(async () => {
        fetchData();
        // 停止条件：状态变为safe或已有修复记录
        if (props.ganderItemData.level === 'safe' || worknote.value?.length > 0) {
            stopPolling();
        }
    }, 2000)
}
const stopPolling = () => {
    if (intervalId) {
        clearInterval(intervalId);
        intervalId = null;
    }
}


// ========================================== 生命周期控制 =======================================
// ==================== 监听level变化 =======================
watch(() => props.ganderItemData, (newVal) => {
    if (newVal) {
        console.log('watch -> ganderItemData');
        
        fetchData();
    }
    if (newVal.level === 'safe') {
        stopPolling()
    } else {
        startPolling()
    }
},{ deep: true },{immediate: true});

// ====================== 清理资源 ===========================
onBeforeUnmount(() => {
    stopPolling();
    if (myChartDanger) {
        myChartDanger.dispose();
        myChartDanger = null;
    }
    if (myChartSafe) {
        myChartSafe.dispose();
        myChartSafe = null;
    }
});

// 添加响应式resize监听
onMounted(() => {
    console.log('bbb',props.ganderItemData);
    fetchData()
    resizeObserver.value = new ResizeObserver(() => {
        if (myChartDanger) {
            myChartDanger.resize();
        }
        if (myChartSafe) {
            myChartSafe.resize();
        }
    });
    
    if (chartRefDanger.value) {
        resizeObserver.value.observe(chartRefDanger.value);
    }
    if (chartRefSafe.value) {
        resizeObserver.value.observe(chartRefSafe.value)
    }
});
</script>

<template>
    <div class="dangerDetail-title">
        <!-- <span class="back">
            <router-link :to="{ name: 'dangerBoard' }" class="nav-link">
                <img src="../assets/icon/返回.png" alt="">
            </router-link>
        </span> -->
        <h1>告警详情</h1>
    </div>
    
    <div class="dangerDetail-content">
        <a-descriptions bordered column="3" class="dangerDetail-card">
            <a-descriptions-item label="告警名称">{{ ganderItemData.name }}</a-descriptions-item>
            <a-descriptions-item label="告警级别">
                <a-tag :color="ganderItemData.level === 'safe' ? 'processing' : ganderItemData.level === 'danger1' ? 'error' : 'warning'">
                        {{ ganderItemData.level === 'safe' ? '已处理' : ganderItemData.level === 'danger1' ? '重要' : '普通' }}
                </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="告警时间">{{ ganderItemData.time }}</a-descriptions-item>
            <a-descriptions-item label="告警内容">{{ ganderItemData.content }}</a-descriptions-item>
        </a-descriptions>

        <div class="dangerChart-safeNote">
            <div class="dangerCharts">
                <!-- ECharts 图表可以在这里添加 -->
                <div ref="chartRefDanger" style="width: 100%; height: 100%;"></div>
            </div>
            <div class="safeNote">
                <h3>修复记录</h3>
                <div class="note-content">
                    <a-list item-layout="horizontal">
                        <a-list-item v-for="(item, index) in safeNote" :key="index">
                            <a-list-item-meta>
                                <template #title>
                                    <span>{{ item.step }}</span>
                                </template>
                                <template #description>
                                    <ul>
                                        <li v-for="(content, cIndex) in item.content" :key="cIndex">{{ content }}</li>
                                    </ul>
                                </template>
                            </a-list-item-meta>
                        </a-list-item>
                    </a-list>
                </div>
            </div>
        </div>
        <div class="safeCharts">
            <div ref="chartRefSafe" style="width: 100%; height: 100%;"></div>
        </div>
    </div>
</template>

<style>
.dangerDetail-content {
    padding-bottom: 20px;
}
.dangerDetail-title {
    width: 100%;
    height: 60px;
    line-height: 60px;
    margin-bottom: 5px;
}
.dangerDetail-title h1{
    margin-bottom: 10px;
    font-size: 36px;
    color: rgb(0, 81, 255);
    font-weight: 750;
    display: inline;
}
.back {
    width: 50px;
    height: 50px;
    display: inline-block;
    margin-right: 20px;
}
.back .nav-link {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-color: #fff;
    text-decoration: none;
}
.back .nav-link img {
    width: 30px;
    height: 30px;
}
.back .nav-link:hover {
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
    transition: box-shadow 0.3s ease;
}
.dangerDetail-card {
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
    transition: box-shadow 0.3s ease;
    border: 0 !important;
}
.dangerChart-safeNote {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
    /* background-color: #e0e0e0; */
}
.dangerChart-safeNote .dangerCharts {
    width: 65%;
    height: 300px;
    padding: 20px 10px 10px;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
    background-color: #fff;
    border-radius: 20px;
}
.dangerChart-safeNote .safeNote {
    width: 33%;
    height: 300px;
    padding: 20px;
    background-color: #fff;
    border-radius: 20px;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
}
.dangerCharts,
.safeNote {
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
}
.safeNote .note-content {
    margin-top: 5px;
    width: 100%;
    height: 230px;
    overflow-y: auto;
}
.safeCharts {
    width: 100%;
    height: 400px;
    padding: 20px 10px 10px;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
    background-color: #fff;
    border-radius: 20px;
    margin-top: 20px;
}
@media screen and (max-width: 1350px) {
    .dangerDetail-title h1 {
        font-size: 32px;
    }
    .dangerChart-safeNote {
        flex-direction: column;
        align-items: center;
    }
    .dangerChart-safeNote .dangerCharts {
        width: 100%;
        height: 250px;
        margin-bottom: 20px;
    }
    .dangerChart-safeNote .safeNote {
        width: 100%;
        height: auto;
    }
    .safeCharts {
        height: 300px;
    }
}

@media screen and (max-width: 750px) {
    .dangerDetail-title {
        text-align: center;
    }
    .dangerDetail-title h1 {
        font-size: 28px;
    }
    .back {
        display: none; /* 隐藏返回按钮 */
    }
    .dangerChart-safeNote {
        flex-direction: column;
        align-items: center;
    }
    .dangerChart-safeNote .dangerCharts {
        width: 100%;
        height: 300px;
        margin-bottom: 15px;
    }
    .dangerChart-safeNote .safeNote {
        width: 100%;
        height: auto;
    }
    .safeNote .note-content {
        height: auto;
    }
    .safeCharts {
        height: 350px;
    }
}
</style>